const transport = require('./mailer')
const db = require("../../database");
const writeLogs = require('./writeLogs');

module.exports = (req, res) => {
    if (!req.query) return res.cc('nothing get')
    const target = req.query['mail'];
    if (!target) return res.cc('get no mail')

    let code = '';
    for (let i=0; i<4; i++) {
        code += Math.floor(Math.random()*10);
    }
    const deadline = (Date.now()+6e5).toString();
    const sendMail = () => {
        transport.sendMail({
            from: '594078370@qq.com',
            subject: 'PICS SHOW 账户验证',
            to: target,
            text: `您的验证码是：${code}，\n如非本人操作，请忽略。`
        }).then(() => {
            writeLogs('request', {
                username: target,
                req: '邮箱验证',
            })
            res.cc('发送成功', 0);
        }).catch(err => res.cc(err))
    }

    let sql = 'update verification set code=?, deadline=? where address = ?';
    db.query(sql, [code, deadline, target], (err, data)=>{
        if (err) return res.cc(err)
        if (data.affectedRows === 0) {
            sql = 'insert into verification (address, code, deadline) values (?,?,?)';
            db.query(sql, [target, code, deadline], (err, data) => {
                if (err) return res.cc(err)
                if (data.affectedRows === 0) return res.cc('数据库插入失败')
                sendMail();
            })
        } else sendMail();
    })
}